package com.chuanjiabao.wisdom;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.databinding.DataBindingUtil;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;

import com.chuanjiabao.wisdom.adapter.ApplicationState;
import com.chuanjiabao.wisdom.adapter.BaseFragmentAdapter;
import com.chuanjiabao.wisdom.application.FApplication;
import com.chuanjiabao.wisdom.bean.FamilyDeatilCallbackBean;
import com.chuanjiabao.wisdom.bean.ReasionInfoCallbackBean;
import com.chuanjiabao.wisdom.bean.RefreshMessageEvent;
import com.chuanjiabao.wisdom.databinding.ActivityMainBinding;
import com.chuanjiabao.wisdom.listener.MainFragmentProxy;
import com.chuanjiabao.wisdom.listener.NetworkCallbackImpl;
import com.chuanjiabao.wisdom.listener.OnBHClickListener;
import com.chuanjiabao.wisdom.service.UpdateService;
import com.chuanjiabao.wisdom.ui.BaseActivity;
import com.chuanjiabao.wisdom.ui.activity.AddFamilyBodyActivity;
import com.chuanjiabao.wisdom.ui.activity.AuthRenZhengActivity;
import com.chuanjiabao.wisdom.ui.activity.FamilyPeopleFilesActivity;
import com.chuanjiabao.wisdom.ui.fragment.IndexFragment;
import com.chuanjiabao.wisdom.ui.fragment.SecondFragment;
import com.chuanjiabao.wisdom.ui.fragment.ThirdFragment;
import com.chuanjiabao.wisdom.ui.view.MainTableView;
import com.chuanjiabao.wisdom.util.BHThreadPool;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.LogUtil;
import com.chuanjiabao.wisdom.util.SpResourceUtil;
import com.chuanjiabao.wisdom.util.SpUtils;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.ToastUtil;
import com.chuanjiabao.wisdom.util.dialog.JoinQueueDialog;
import com.chuanjiabao.wisdom.util.dialog.VersionDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Response;

import static com.chuanjiabao.wisdom.bean.Constants.REQUEST_CODE;
import static com.chuanjiabao.wisdom.bean.Constants.UPDATE_LOAD_HOME;
import static com.chuanjiabao.wisdom.bean.Constants.UPDATE_LOAD_PERSON;

public class MainActivity extends BaseActivity implements ViewPager.OnPageChangeListener, MainTableView.OnTableChangedListener {

    ActivityMainBinding binding;
    private int currentAt = 0;
    private ApplicationState applicationState = new ApplicationState();
    private List<Fragment> fragment = new ArrayList<>();

    private NetworkCallbackImpl mCallback;

    //上传头像服务
    private Intent mServiceIntent;
    private UpdateService updateService;

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            updateService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            updateService = ((UpdateService.MyBinder) service).getService();
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        bindService(mServiceIntent, conn, BIND_AUTO_CREATE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(com.chuanjiabao.wisdom.R.color.F1F2530));
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        EventBus.getDefault().register(this);
        initView();

        getSTS();
        updateRegisationID();
        getUpdate();
    }

    private void initView() {
        SpUtils.put("module_islogin", "1");
        mServiceIntent = new Intent(this, UpdateService.class);
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(UpdateService.HEART_BEAT_ACTION);
        mIntentFilter.addAction(UpdateService.MESSAGE_ACTION);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mCallback = new NetworkCallbackImpl();
            ConnectivityManager mConnectivityManager =
                    (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            mConnectivityManager.registerDefaultNetworkCallback(mCallback);
        }
    }

    private void initData() {
        BaseFragmentAdapter fragmentAdapter = new BaseFragmentAdapter(getSupportFragmentManager());
        fragment.add(new IndexFragment());
        fragment.add(new SecondFragment());
        fragment.add(new ThirdFragment());
        //noinspection unchecked
        fragmentAdapter.addData(fragment);
        binding.viewPager.setAdapter(fragmentAdapter);
        binding.viewPager.setCurrentItem(currentAt);
        binding.viewPager.addOnPageChangeListener(MainActivity.this);
        binding.mtModule.setOnTableChangedListener(MainActivity.this);
    }

    @Subscribe
    public void onMessageEvent(RefreshMessageEvent event) {
        if (TextUtils.equals("main", event.getType())) {
            switch (event.getId()) {
                case "1":
                    binding.mtModule.onClick(0);
                    break;
                case "2":
                    ReasionInfoCallbackBean.DataBean bean = (ReasionInfoCallbackBean.DataBean) SpUtils.getBean("module_reasion");
                    if (1 == bean.getSecret_on()) {
                        startActivityForResult(new Intent(MainActivity.this, AuthRenZhengActivity.class), REQUEST_CODE);
                    } else binding.mtModule.onClick(1);
                    break;
                case "3":
                    binding.mtModule.onClick(2);
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbindService(conn);
    }

    /**
     * 设置跳转界面
     */
    public void setCurrentAt(int position) {
        binding.viewPager.setCurrentItem(position);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        if (binding.mtModule != null) {
            binding.mtModule.onClick(binding.viewPager.getCurrentItem());
        }
        if (applicationState.isMainSliding() && position == 1) {
            applicationState.setMainSliding(false);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (!applicationState.isMainSliding() && state != ViewPager.SCROLL_STATE_IDLE) {
            applicationState.setMainSliding(true);
        }
    }

    @Override
    public void onTableChanged(int index) {
        if (currentAt != index) {
            currentAt = index;
            binding.viewPager.setCurrentItem(index, false);
        } else {
            if (fragment.get(index) instanceof MainFragmentProxy) {
                ((MainFragmentProxy) fragment.get(index)).scrollToTop();
            }
        }
    }

    @Override
    public boolean onTabTouched() {
        ReasionInfoCallbackBean.DataBean bean = (ReasionInfoCallbackBean.DataBean) SpUtils.getBean("module_reasion");
        if (1 == bean.getSecret_on()) {
            startActivityForResult(new Intent(MainActivity.this, AuthRenZhengActivity.class), REQUEST_CODE);
            return true;
        } else return false;
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
    }

    private List<LocalMedia> selectList = new ArrayList<>();
    //设置私密/家        relation 家上传关联到某人
    String homeOrPerson, homeId, relation = "";

    public void setInfo(String homeId) {
        this.homeOrPerson = UPDATE_LOAD_HOME;
        this.homeId = homeId;
    }

    //上传私密资料
    public void updatePersonResource(String homeId, String relation) {
        this.homeOrPerson = UPDATE_LOAD_PERSON;
        this.homeId = homeId;
        this.relation = relation;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                selectList = PictureSelector.obtainMultipleResult(data);
                Runnable runnable = () -> {
                    for (LocalMedia media : selectList) {
                        SystemClock.sleep(1000);
                        updateService.setInfo(homeOrPerson, homeId, SpResourceUtil.getToken(), relation, media.getPath());
                    }
                };
                BHThreadPool.getInstance().executeTask(runnable);

                if (!selectList.isEmpty()) showHintDialog();
            } else if (requestCode == REQUEST_CODE) {
                String result = data.getStringExtra("module_status");
                if ("succ".equals(result)) {
                    setCurrentAt(1);
                }
            }
        } else if (resultCode == 101) {
            String path = data.getStringExtra("path");
            LogUtil.e("图片路径-->" + path);
            updateService.setInfo(homeOrPerson, homeId, SpResourceUtil.getToken(), relation, path);

            if (!TextUtils.isEmpty(path)) showHintDialog();
        } else if (resultCode == 102) {
            String url = data.getStringExtra("url");
            LogUtil.e("视频路径-->" + url);
            updateService.setInfo(homeOrPerson, homeId, SpResourceUtil.getToken(), relation, url);

            if (!TextUtils.isEmpty(url)) showHintDialog();
        } else if (resultCode == 103) {
            ToastUtil.showToast("请检查相机权限");
        }
    }

    private void showHintDialog() {
        JoinQueueDialog dialog = new JoinQueueDialog(MainActivity.this);
        dialog.show();
    }

    private void showUpdateDialog(String hint, boolean isForce) {
        new VersionDialog(this)
                .setTitle("版本更新")
                .setContent(hint)
                .setYesHint("更新")
                .setNoHint("取消")
                .setForce(isForce)
                .setOnBHClickListener(new OnBHClickListener() {
                    @Override
                    public void onConfirmClick() {
                        Uri uri = Uri.parse("market://details?id=com.chuanjiabao.wisdom");
                        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(goToMarket);
                    }

                    @Override
                    public void onCloseClick() {
                        initData();
                    }
                })
                .show();
    }

    private void getUpdate() {
        HTTPAPI.getInstance().getUpdate(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(MainActivity.this, s);
                } else {
                    try {
                        JSONObject json = new JSONObject(s);
                        if (json.has("data")) {
                            JSONObject obj = json.getJSONObject("data");

                            String current = StringUtil.getVersion(MainActivity.this);
                            String version = obj.optString("android_ver");
                            String hint = obj.optString("android_update_des");
                            int forceType = obj.getInt("force_update");

                            int versionNow = Integer.parseInt(current.replace(".", ""));
                            int versionget = Integer.parseInt(version.replace(".", ""));
                            if (versionget > versionNow) showUpdateDialog(hint, forceType == 1);
                            else initData();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        initData();
                    }
                }
            }
        });
    }

    private void getSTS() {
        HTTPAPI.getInstance().getSTS(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(MainActivity.this, s);
                }
            }
        });
    }

    private void updateRegisationID() {
        HTTPAPI.getInstance().updateRegisationID(
                UUID.randomUUID().toString().replace("-", ""),
                FApplication.getInstance().getDeviceToken(),
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (!StringUtil.isFail(s)) {
                            StringUtil.showFail(MainActivity.this, s);
                        }
                    }
                }
        );
    }

    public void toSelectImgAndVideo() {
        PictureSelector.create(MainActivity.this)
                .openGallery(PictureMimeType.ofAll())
                .theme(R.style.picture_default_style)
                .maxSelectNum(9)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .previewVideo(true)
                .enablePreviewAudio(true)
                .isCamera(false)
                .isZoomAnim(true)
                .imageFormat(PictureMimeType.PNG)
                .setOutputCameraPath("/CustomPath")
                .enableCrop(false)
                .compress(false)
                .synOrAsy(true)
                .glideOverride(160, 160)
                .isGif(true)
                .freeStyleCropEnabled(true)
                .openClickSound(true)
                .selectionMedia(selectList)
                .withAspectRatio(3, 2)
                .previewEggs(true)
                .minimumCompressSize(100)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @JavascriptInterface
    public void familyDetail(final String userId) {
        getFamilyDetail(userId);
    }

    @JavascriptInterface
    public void addFamilyBody(final String x, final String y) {
        Intent intent = new Intent(MainActivity.this, AddFamilyBodyActivity.class);
        intent.putExtra("module_y", y);
        intent.putExtra("module_x", x);
        intent.putExtra("module_funcation", "add");
        startActivity(intent);
    }

    //获取家信息，更新个人信息
    public void getFamilyDetail(final String peopleId) {
        HTTPAPI.getInstance().getFamilyDetail(homeId, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(MainActivity.this, s);
                } else {
                    try {
                        FamilyDeatilCallbackBean callbackBean = GsonUtil.GsonToBean(s, FamilyDeatilCallbackBean.class);
                        for (FamilyDeatilCallbackBean.DataBean dataBean : callbackBean.getData()) {
                            for (FamilyDeatilCallbackBean.DataBean.MembersBean membersBean : dataBean.getMembers()) {
                                if (peopleId.equals(membersBean.getD_id() + "")) {
                                    if (TextUtils.isEmpty(membersBean.getD_name())) {
                                        Intent intent = new Intent(MainActivity.this, AddFamilyBodyActivity.class);
                                        intent.putExtra("module_funcation", "look");
                                        intent.putExtra("module_bean", membersBean);
                                        startActivity(intent);
                                    } else {
                                        Intent intent = new Intent(MainActivity.this, FamilyPeopleFilesActivity.class);
                                        SpUtils.put("module_peopleId", peopleId);
                                        intent.putExtra("module_homeId", homeId);
                                        intent.putExtra("module_funcation", "add");
                                        startActivity(intent);
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private Long exitTime = 0L;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            ToastUtil.showToast("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                if (mCallback != null) {
                    ConnectivityManager mConnectivityManager =
                            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    mConnectivityManager.unregisterNetworkCallback(mCallback);
                }
            }

            Intent intentDelete = new Intent();
            intentDelete.setAction("MODULE_ABOUT_RELATION");
            intentDelete.putExtra("module_funcation", "4");
            sendBroadcast(intentDelete);

            super.onBackPressed();
        }
    }

}